package net.homelinux.chaoswg.io.renga.krypto.animations.Subtract;

import java.awt.GridLayout;
import java.util.Observable;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;

import net.homelinux.chaoswg.io.renga.core.registries.GlobalPropertyRegistry;
import net.homelinux.chaoswg.io.renga.krypto.datatypes.numerical.UnsignedNBit;

public class SubtractStateChanger extends Observable implements Runnable {
    final SubtractState initialState;
    JLabel firstOperandsDisplay;
    JLabel secondOperandsDisplay;
    JLabel resultDisplay;
    JFrame jw;


    public SubtractStateChanger (final SubtractState initialState) {
        this.initialState = initialState;
        
        jw = new JFrame ("Subtract");
        jw.getContentPane().add(getPanel());
        jw.setLocationRelativeTo(null);
        
        jw.setSize(500, 100);

    }
    
    private JPanel getPanel() {
        JPanel toReturn = new JPanel (new GridLayout (3,1));
        toReturn.add (firstOperandsDisplay = new JLabel (initialState.getMinuend().toString()));
        toReturn.add (secondOperandsDisplay = new JLabel (initialState.getSubtrahend().toString()));
        toReturn.add (resultDisplay = new JLabel (initialState.getResult().toString()));

        firstOperandsDisplay.setHorizontalAlignment(JLabel.RIGHT);
        secondOperandsDisplay.setHorizontalAlignment(JLabel.RIGHT);
        resultDisplay.setHorizontalAlignment(JLabel.RIGHT);

        toReturn.setBorder(new BevelBorder (BevelBorder.RAISED));
        
        return toReturn;
    }
    
    private void setNew () {
        firstOperandsDisplay.setText (initialState.getMinuend().toString());
        firstOperandsDisplay.paintImmediately(firstOperandsDisplay.getBounds());
        secondOperandsDisplay.setText (initialState.getSubtrahend().toString());
        secondOperandsDisplay.paintImmediately(firstOperandsDisplay.getBounds());
        resultDisplay.setText (initialState.getResult().toString());
        resultDisplay.paintImmediately(firstOperandsDisplay.getBounds());
    }
    
    public void run() {
        int delay = ((Integer)GlobalPropertyRegistry.getGlobalPropertyRegistry().getProperty("animationSpeed")) * 100;

        jw.setVisible(true);
        UnsignedNBit minuend = initialState.getMinuend();
        UnsignedNBit subtrahend = initialState.getSubtrahend();
        
        setNew ();        
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {}
        
        initialState.setResult(minuend.subtract(subtrahend));

        setNew ();        
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {}
    }
    
    public void close () {
        jw.dispose();
    }
}
